<?php
include "Team.php";

class TeamDAO extends DataLayer {
	/**
	* @desc Construtor da Classe
 	*/
	function __construct($lk){
		$this->lk = $lk;	
	}

	public function getTeams($id=0, $status=null, $page=0){

		if($status == NULL)
			$status = array(1);
	
		$this->sql ="	SELECT
							e.id_equipe, e.nome, e.status, e.data,
							COALESCE((
								SELECT
									count(p.id_projeto)
								FROM
									projetos p
								WHERE
									p.status = 1 AND EXISTS (
										SELECT 1
										FROM
											sprints s
										WHERE
											p.id_projeto = s.id_projeto AND
											e.id_equipe = s.id_equipe
									)
								GROUP BY p.id_projeto
							),0) projects,
							(
								SELECT
									COUNT(eu.id_usuario)
								FROM
									equipes_usuarios eu
								INNER JOIN
									usuarios u ON eu.id_usuario = u.id_usuario
								WHERE
									eu.id_equipe = e.id_equipe AND u.status = 1
							) users
						FROM
							equipes e
						WHERE
							1 = 1";

		if(count($status) > 0)	
			$this->sql .= " AND	e.status IN (".implode(",",$status).")";
	
		if($id > 0)						
			$this->sql .= " AND e.id_equipe = ".$id;
		
		$this->sql .= " ORDER BY e.nome";

		if($page > 0){
			$page = (int)$page;
			$page--;
			if($page < 0)
				$page = 0;
			else
				$page *= PAGINATION;

			$this->sql .= " LIMIT ".$page.",".PAGINATION;
		}
		
		$this->result = parent::select($this->sql);
		$teamsList = NULL;
		
		if(count($this->result) > 0){
			$i = 0;
			foreach($this->result as $row){
				$teamsList[$i] = new Team();
				$teamsList[$i]->setDadosDB($row);

				$i++;
			}
		}
		
		return $teamsList;
	}

	public function save(Team $obj){
		if($obj != NULL){
			$dbObj = $obj->fieldsDBObj;
			unset($dbObj["id_equipe"]);
			if($obj->id > 0){
				parent::update("equipes",$dbObj,"id_equipe = ".$obj->id);
				return $obj->id;
			}else{
				return parent::insert("equipes",$dbObj,"data");
			}
		}else{
			return 0;
		}
	}

	public function getUsersTeam(){
		$this->sql ="	SELECT 
							e.id_equipe id,
							(
							SELECT 
								COUNT(eu.id_usuario)
							FROM
								equipes_usuarios eu
							WHERE
								eu.id_equipe = e.id_equipe
							) users
						FROM 
							equipes e
						WHERE
							e.status IN (0,1)";
		
		return parent::select($this->sql);
	}

	public function deleteTeam($id=0){
		if($id > 0){
			$rsTeam = $this->getTeams($id);

			if(count($rsTeam) > 0){
				if($rsTeam[0]->projects > 0){
					return -1;
				}else{
					$dados["status"] = -1;
					return parent::update("equipes", $dados, "id_equipe=".$id);
				}				
			}
		}

		return 0;
	}
}

?>